//
//  YSSecuritiesManager.m
//  GuBoShi
//
//  Created by zhanglu on 2017/3/22.
//  Copyright © 2017年 YiShi. All rights reserved.
//

#import "YSSecuritiesManager.h"
#import "YSSecurities.h"
#import "YSSecuritiesDB.h"
#import "EFSChartSocketManager.h"

@interface YSSecuritiesManager()
@property (nonatomic, strong) NSDictionary *quoteCacheInfo;

@end

@implementation YSSecuritiesManager

+ (instancetype) sharedManager {
    static YSSecuritiesManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _trdDay = @"";
        NSString * plistPath = [[NSBundle mainBundle] pathForResource:@"LGQuoteCache" ofType:@"plist"];
        if ([[YSRequestConfig shared].serviceKey isEqualToString:@"test_ys"]){
            plistPath = [[NSBundle mainBundle] pathForResource:@"LGTestQuoteCache" ofType:@"plist"];
        }
        _quoteCacheInfo = [NSDictionary dictionaryWithContentsOfFile:plistPath];
//        NSLog(@"品种缓存:%@",_quoteCacheInfo);
    }
    return self;
}


- (RACSignal *)fetchSecurities
{
    @weakify(self);
    RACReplaySubject *subject = [RACReplaySubject subject];
    YSRequest *request = [YSRequest requestWithName:@"lg.queryInstCode"];
    request.requestSerializerType = YSRequestSerializerTypeJSON;
    NSString *verStr = [[YSSecuritiesDB sharedManager] getCodeVersion];
    [request sendWithParameters:@{@"Ver":objectOrEmptyStr(verStr)} delegate:self success:^(id _Nonnull response) {
        @strongify(self);
//                [response writeToFile:@"/Users/wangqingxue/Desktop/LGTestQuoteCache.plist" atomically:YES];
        
        NSNumber *rcNum = response[@"errorCode"];
        LGlog(@"__码表信息:__url:%@__请求版本号:%@__errorCode:%@",request.requestUrl,verStr,rcNum);

        if ([rcNum.description isEqualToString:@"0"]) {
            
            LGlog(@"__success___码表更新成功");
            [self saveQuoteDataWithResponse:response subject:subject];
            
        }else if([rcNum.description isEqualToString:@"17"]){
            LGlog(@"__码表信息已经是最新");
            [subject sendNext:nil];
            [subject sendCompleted];
            
        }else {
            LGlog(@"__errer___码表更新失败");
            [self saveQuoteDataWithResponse:self.quoteCacheInfo subject:subject];
            
        }
    } failure:^(YSRequest * _Nonnull request) {
        LGlog(@"__errer___码表更新失败");
        LGlog(@"__码表信息:__url:%@__请求版本号:%@",request.requestUrl,verStr);
        [self saveQuoteDataWithResponse:self.quoteCacheInfo subject:subject];
    }];
    return subject;
}

- (void) saveQuoteDataWithResponse:(NSDictionary *)response subject:(RACReplaySubject *)subject
{
    NSArray *arr = [MTLJSONAdapter modelsOfClass:[YSSecurities class] fromJSONArray:response[@"data"] error:nil];
    
    if (!arr.count) {
        LGlog(@"__errer__码表个数返回0");
        [subject sendNext:nil];
        [subject sendCompleted];
        return;
    }

    if ([[YSSecuritiesDB sharedManager] deleteQuoteData]) {
        NSArray * dataArray = response[@"data"];
        if (dataArray.count > 0) {
            BOOL result = [[YSSecuritiesDB sharedManager] insertData:arr];
            if (result) {
                
                YSSecurities *quote  = arr[0];
                self.trdDay = objectOrEmptyStr(quote.TraDate);
                
                //更新quoteList
                [[EFSChartSocketManager sharedChartSocketController].quoteList reloadDataWithDB];
                
                //更新版本号
                self.verStr = response[@"version"];
                [[YSSecuritiesDB sharedManager] updateCodeVersion:self.verStr.length ? self.verStr : @"19370101"];
                
                [subject sendNext:nil];
                [subject sendCompleted];
                LGlog(@"__success__码表插入成功__版本号__%@",self.verStr);
            }else{
                LGlog(@"__errer__码表插入失败");
            }
        }
        
       
    }

    
}


+ (RACSignal *)querySecuritiesWithString:(NSString *)string
{
    RACReplaySubject *subject = [RACReplaySubject subject];
    NSPredicate *predChar = [NSPredicate predicateWithFormat:@"SELF MATCHES '^[A-Za-z]+$'"];
    NSPredicate *predNum = [NSPredicate predicateWithFormat:@"SELF MATCHES '^[0-9]+$'"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0), ^{
        
        NSArray *arr;
//        if ([predNum evaluateWithObject:string]) {// 全部是数字 股票代码 （搜股票代码）
//            arr = [[YSSecuritiesDB sharedManager] getDataWithNumberFromDB:string limit:@"50"];
//       }
//       else if ([predChar evaluateWithObject:string]) { // 全部是字符 （搜拼音）
//            arr = [[YSSecuritiesDB sharedManager] getDataWithPinYinFromDB:string limit:@"50"];
//        }
//        else {  // 汉字或其他混合，转换成拼音后搜拼音
//            arr = [[YSSecuritiesDB sharedManager] getDataWithPinYinFromDB:[YSSecuritiesManager transform:string] limit:@"50"];
//        }
        arr = [[YSSecuritiesDB sharedManager] getDataWithNumberAndNameFromDB:string limit:@"50"];
        
        if (arr) {
            [subject sendNext:arr];
            [subject sendCompleted];
        }
        else {
            [subject sendError:nil];
        }
    });
    return subject;
}

+ (RACSignal *)querySecuritiesListWithEis:(NSArray *)list {
    RACReplaySubject *subject = [RACReplaySubject subject];
    return subject;
}

+ (RACSignal *)querySecuritiesWithEi:(NSString *)Ei
{
    RACReplaySubject *subject = [RACReplaySubject subject];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0), ^{
            YSSecurities *item = [[YSSecuritiesDB sharedManager] getDataWithEiFromDB:Ei];
            if (item) {
                [subject sendNext:item];
                [subject sendCompleted];
            }
            else {
                [subject sendError:nil];
            }
//    });
    return subject;
}

+ (RACSignal *)queryTransferParameterSecuritiesWithEi:(NSString *)Ei
{
    RACReplaySubject *subject = [RACReplaySubject subject];
    //    dispatch_async(dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0), ^{
    YSSecurities *item = [[YSSecuritiesDB sharedManager] getDataWithTransferParameterFromDB:Ei];
    if (item) {
        [subject sendNext:item];
        [subject sendCompleted];
    }
    else {
        [subject sendError:nil];
    }
    //    });
    return subject;
}

+ (NSString *)transform:(NSString *)chinese
{
    NSMutableString *pinyin = [chinese mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    NSLog(@"%@", pinyin);
    return [[pinyin uppercaseString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

+ (void)updateSecuritiesTableModel:(NSArray<YSSecurities *> *)securitiesList
{
    [securitiesList enumerateObjectsUsingBlock:^(YSSecurities * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.isAdded = ([obj.isAdded isEqualToString:@"0"] ? @"1" : @"0");
    }];
    [[YSSecuritiesDB sharedManager] updateDataToListAdded:securitiesList];
}

+ (void)insertFavoriteListModel:(YSSecurities *)model
{
    [YSSecuritiesManager updateSecuritiesTableModel:@[model]];
    [[YSSecuritiesDB sharedManager] insertDataToFavoriteList:model];
}

+ (RACSignal *)queryFavoriteSecurities
{
    RACReplaySubject *subject = [RACReplaySubject subject];
    dispatch_async(dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0), ^{
//        NSArray *arr;
//
//        arr = sec.getFavoriteDataFromDB(50);
//        if (arr) {
//            [subject sendNext:arr];
//        }
//        else {
//            [subject sendError:nil];
//        }
    });
    return subject;
}

+ (RACSignal *)deleteFavoriteSecuritiesModel:(NSArray<YSSecurities *> *)SecuritiesList
{
    RACReplaySubject *subject = [RACReplaySubject subject];
    dispatch_async(dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0), ^{
//        YSSecuritiesSQLite sec;
//        BOOL isDelete = sec.deleteDataFromFavoriteList(SecuritiesList);
//        if (isDelete) {
//            [subject sendNext:@"1"];
//            [YSSecuritiesManager updateSecuritiesTableModel:SecuritiesList];
//        }
//        else {
//            [subject sendError:nil];
//        }
    });
    return subject;
}

#pragma mark - property
- (NSMutableArray *)stockMarket {
    if(!_stockMarket){
        _stockMarket = [NSMutableArray arrayWithCapacity:10];
    }
    return _stockMarket;
}
@end
